package com.englishtest.city.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.util.WebUtils;

import com.englishtest.base.EnglishtestException;
import com.englishtest.base.GlobalConstant;
import com.englishtest.base.PageHelper;
import com.englishtest.base.Paginater;
import com.englishtest.city.service.CityService;
import com.englishtest.city.service.CityServiceFactory;
import com.englishtest.pojos.City;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CityAction extends ActionSupport {
	private City city;
	
	public String execute() {
		return "";
	}
	
	public String listCity() throws Exception {
		Map para = ActionContext.getContext().getParameters();
		HttpServletRequest request = ServletActionContext.getRequest();
		String searchWord = ServletRequestUtils.getStringParameter(request, "searchWord");
		int isValid = ServletRequestUtils.getIntParameter(request, "isValid", GlobalConstant.BOOLEAN_ALL);
		Paginater paginater = PageHelper.getDefaultPaginater(request);
		
		CityService cityService = CityServiceFactory.getCityService();
		List cityList = cityService.searchCity(searchWord, isValid, paginater);
		ActionContext.getContext().put("cityList", cityList);
		ActionContext.getContext().put("pageProperty", PageHelper.getPageProperty(paginater));
		return "listCity";
	}
	
	public String saveCity() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		City c = getCityFromId(ServletRequestUtils.getStringParameter(request, "cityId"));
		if(WebUtils.hasSubmitParameter(request, "save")) {
			CityService cityService = CityServiceFactory.getCityService();
			if(c == null) {
				c = new City();
			}
			c.setCityName(city.getCityName().trim());
			c.setCityCode(city.getCityCode().trim());
			c.setIfValid(city.getIfValid());
			
			try {
				cityService.saveCity(c);
			} catch (Exception e) {
				ServletActionContext.getResponse().getWriter().write("0");
				return null;
			}			
			ServletActionContext.getResponse().getWriter().write(String.valueOf(c.getId()));
			return null;
		}
		if(c != null) {
			ActionContext.getContext().put("city", c);
		}
		return "saveCity";
	}
	
	private City getCityFromId(String cityId) throws EnglishtestException {
		if(StringUtils.isBlank(cityId)) return null;
		CityService cityService = CityServiceFactory.getCityService();
		return cityService.getCity(Integer.decode(cityId));
	}

	public City getCity() {
		return city;
	}

	public void setCity(City city) {
		this.city = city;
	}

	
	
}
